<?php

class ResultPagination {
	protected $base_link = "";
	protected $cur_page = 0;
	protected $last_page = 0;
	protected $pages_around = 10;
	
	protected static $btnFirstPage = "images/b_firstpage.png";
	protected static $btnLastPage = "images/b_lastpage.png";
	protected static $btnPrevPage = "images/b_prevpage.png";
	protected static $btnNextPage = "images/b_nextpage.png";
	protected static $pageTag = '$PAGE';
	
	public function __construct($base_link, $cur_page, $last_page, $pages_around = 10) {
		$this->setBaseLink($base_link);
		$this->setLastPage($last_page);
		$this->setCurrentPage($cur_page);
		$this->setPagesAround($pages_around);
	}
	
	public function setPagesAround($around) {
		if ($around >= 0)
			$this->pages_around = $around;
	}
	
	public function getPagesAround() {
		return $this->pages_around;
	}
	
	public function setBaseLink($url) {
		$this->base_link = $url;
	}
	
	public function getBaseLink() {
		return $this->base_link;
	}
	
	public function setCurrentPage($page) {
		if ($page < $this->last_page) 
			$this->cur_page = $page;
	}
	
	public function getCurrentPage() {
		return $this->cur_page;
	}
	
	public function setLastPage($page) {
		if ($page >= 0) {
			$this->last_page = $page;
			if ($this->cur_page >= $this->last_page)
				$this->cur_page = $this->last_page - 1;
		}
	}
	
	public function getLastPage() {
		return $this->last_page;
	}
	
	private function getLink($page) {
		return str_replace(self::$pageTag, $page, $this->base_link);
	}
	
	public function toHtml() {
		$prev_link = "";
		$next_link = "";
		$links = "";

		$html = '<a href="'.$this->getLink(0).'"><img src="'.self::$btnFirstPage.'"></a>&nbsp;';
		$start = max($this->cur_page - ($this->pages_around / 2), 0);
		if (($start + $this->pages_around) > $this->last_page) {
			$stop = $this->last_page;
			$start = max($stop - $this->pages_around, 0);
		}
		else
			$stop  = $start + $this->pages_around;
		for ($j = $start; $j < $stop; $j++) {
			$links .= "&nbsp;";
			$href = 'href="'.$this->getLink($j).'"';
			if ($j == ($this->cur_page - 1))
				$prev_link = '&nbsp;<a id="prev" '.$href.'><img src="'.self::$btnPrevPage.'"></a>&nbsp;';
			elseif ($j == ($this->cur_page + 1))
				$next_link = '&nbsp;&nbsp;<a id="next" '.$href.'><img src="'.self::$btnNextPage.'"></a>&nbsp;';
			if ($j == $this->cur_page) 
				$links .= ($j + 1);
			else
				$links .= "<a $href>".($j + 1)."</a>";
		}
		$html .= $prev_link.$links.$next_link;
		$html .= '&nbsp;<a href="'.$this->getLink($this->last_page - 1).'"><img src="'.self::$btnLastPage.'"></a>';
		return $html;
	}
}
?>
